import sys,os,time
from operator import mod
from math import ceil
from pathlib import Path
import cv2
import tkinter as tk
from tkinter import *
from tkinter import ttk
from tkinter.ttk import Frame
from PIL import Image, ImageTk

try:
    media_file = sys.argv[1]
except:
    media_file = '1.mp4'


if not Path('add').exists():
    Path('add').mkdir(mode=0o777,parents=False,exist_ok=False)
if not Path('retrieve').exists():
    Path('retrieve').mkdir(mode=0o777,parents=False,exist_ok=False)

white_zero = cv2.imread('template/white_0.jpg')
white_one = cv2.imread('template/white_1.jpg')
white_two = cv2.imread('template/white_2.jpg')
white_three = cv2.imread('template/white_3.jpg')
white_four = cv2.imread('template/white_4.jpg')
white_five = cv2.imread('template/white_5.jpg')
white_six = cv2.imread('template/white_6.jpg')
white_seven = cv2.imread('template/white_7.jpg')
white_eight = cv2.imread('template/white_8.jpg')
white_night = cv2.imread('template/white_9.jpg')
black_zero = cv2.imread('template/black_0.jpg')
black_one = cv2.imread('template/black_1.jpg')
black_two = cv2.imread('template/black_2.jpg')
black_three = cv2.imread('template/black_3.jpg')
black_four = cv2.imread('template/black_4.jpg')
black_five = cv2.imread('template/black_5.jpg')
black_six = cv2.imread('template/black_6.jpg')
black_seven = cv2.imread('template/black_7.jpg')
black_eight = cv2.imread('template/black_8.jpg')
black_night = cv2.imread('template/black_9.jpg')
nums = [white_zero,white_one,white_two,white_three,white_four,white_five,white_six,white_seven,white_eight,white_night,black_zero,black_one,black_two,black_three,black_four,black_five,black_six,black_seven,black_eight,black_night]

def timing(position):
    current = position//25
    current_sec = mod(current,60)
    current_min = current // 60
    if current_min >= 60:
        current_min = mod(current_min, 60)
    current_hour = current // 3600
    current_time = ''.join([str(current_hour).zfill(2),':',str(current_min).zfill(2),':',str(current_sec).zfill(2)])

    return current_time

def get_last_anno():
    with open(annofile,'r') as f:
        tags = f.read().splitlines()
    index = -1
    if tags[index].isalpha():
        index -= 1 
    end_anno = tags[index]
    if '_' in end_anno:
        end_anno = 'NULL'

    return end_anno

def load_tag_state():
    with open(annofile,'r') as f:
        tags = f.read().splitlines()
    tag_states = [line for line in tags if line.isalpha()]
    try:
        tag_state_current = tag_states[-1]
    except:
        tag_state_current = 'None'

    return tag_state_current

def get_position(time):
    try:
        current_hour,current_min,current_sec = time.split(':')
        current_frame = int(fps * (int(current_hour) * 3600 + int(current_min) * 60 + int(current_sec)))
    except:
        current_frame = position

    return current_frame

def get_number(num_img):
    mean,stddv = cv2.meanStdDev(num_img)
    *_,channels = num_img.shape
    #imgMean = 121
    imgMean = sum(mean)/channels
    _,num_img = cv2.threshold(num_img,imgMean,255,cv2.THRESH_BINARY)
    results = [cv2.matchTemplate(num_img,template,cv2.TM_CCOEFF_NORMED).astype(float) for template in nums]

    return mod(results.index(max(results)),10)

white 		= "#ffffff"
lightBlue2 	= "#adc5ed"
font 		= "Constantia"
fontButtons = (font, 12)
maxWidth  	= 800
maxHeight 	= 480

videoWidth = 760
videoHeight = 400

#Graphics window
mainWindow = tk.Tk()
mainWindow.configure(bg=lightBlue2)
mainWindow.geometry('%dx%d+%d+%d' % (maxWidth,maxHeight,0,0))
mainWindow.resizable(0,0)

mainFrame = Frame(mainWindow)
mainFrame.place(x=20, y=20)                

#Capture video frames
lmain = tk.Label(mainFrame)
lmain.grid(row=0, column=0)

closeButton = Button(mainWindow, text = "CLOSE", font = fontButtons, bg = white, width = 20, height= 1)
closeButton.configure(command= lambda: mainWindow.destroy())              
closeButton.place(x=270,y=430)	

annofile = ''.join([media_file,'.anno'])
try:
    media = cv2.VideoCapture(media_file)
except:
    print("can't open media file")
fps = media.get(cv2.CAP_PROP_FPS)
frames = int(media.get(cv2.CAP_PROP_FRAME_COUNT))

total_time = timing(frames)
loop_flag = 0
clip_flag = 0
edit_flag = 0
position = 0
success = 0

media = cv2.VideoCapture(media_file)
def on_key_event(event):
    print('you pressed %s'% event.key)
    key_press_handler(event, canvas, toolbar)
    canvas.mpl_connect('key_press_event', on_key_event)

def show_frame():
    success, frame = media.read()
    global position
    if success and position < frames:
        position += 1
        cv2image   = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
        img   = Image.fromarray(cv2image).resize((videoWidth, videoHeight))
        imgtk = ImageTk.PhotoImage(image = img)
        lmain.imgtk = imgtk
        lmain.configure(image=imgtk)
        lmain.after(10, show_frame)
        #print(position)
    else:
        print("position is :",position)
        media.release()
    return position


position = show_frame()  #Display
mainWindow.mainloop()  #Starts GUI
